package com.jm.springboot21.controller;


import com.jm.springboot21.pojo.Result;
import com.jm.springboot21.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@CrossOrigin("*")
public class UploadController {

//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile file) throws IOException {
////        log.info("文件上传:{},{},{}",username,age,file);   db.sql
//        //获取原文件名
//        String originalFilename = file.getOriginalFilename();
//        //拼接新文件名
//        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//        //将文件保存在服务端 D:/upload1
//        file.transferTo(new File("D:/upload1/"+newFileName));
//        return Result.success();
//    }

    private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private String bucketName = "jm-oss-cn";

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传: {}", file.getOriginalFilename());
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = AliyunOSSUtils.upload(endpoint, bucketName, file.getBytes(), extName);
        System.out.println("url = " + url);
        return Result.success(url);
    }
}
